package com.api.user.service.impl;

import com.api.common.ImageUploadUtil;
import com.api.common.config.UploadConfig;
import com.api.core.config.AuthUser;
import com.api.core.response.ResultEnum;
import com.api.user.dao.UserImageMapper;
import com.api.user.model.UserImage;
import com.api.user.service.UserImageService;
import com.api.core.service.AbstractService;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import com.api.common.JSONUtils;
import com.api.core.response.Result;
import com.api.core.response.ResultGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * Created by wanghuiwen on 2021/04/14.
 */
@Service
@Transactional
public class UserImageServiceImpl extends AbstractService<UserImage> implements UserImageService {
    @Resource
    private UserImageMapper userImageMapper;

    @Resource
    private UploadConfig uploadConfig;
    @Override
    public Result list(String search, String order, Integer page, Integer size){
        Map<String, Object> params = JSONUtils.json2map(search);
        Map<String, Object> orderParams = JSONUtils.json2map(order);
        for (String key : orderParams.keySet()) {
                if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
                if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
            }
        PageHelper.startPage(page, size);
        List<Map<String, Object>> res = userImageMapper.baseList(params, orderParams);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public Result listUser(Long uid) {
        List<Map<String, Object>> res = userImageMapper.list(uid);
        return ResultGenerator.genSuccessResult(res);
    }

    @Override
    public Result add(HttpServletRequest request, AuthUser authUser) {

        UserImage userImage = new UserImage();
        userImage.setUserId(authUser.getId());
        String up = "img/";
        try {
            String spath = ImageUploadUtil.upload(request, uploadConfig.getFilePath() + up);
            userImage.setUrl(uploadConfig.getPrefix() + up + spath.split(",")[0]);
            save(userImage);
            return ResultGenerator.genResultAndData(ResultEnum.UPLOADED,uploadConfig.getPrefix() + up + spath.split(",")[0]);
        } catch (IOException e) {
            return ResultGenerator.genResult(ResultEnum.UPLOADED_FAIL);
        }
    }
}
